import { createRouter, createWebHistory } from 'vue-router';
import rules from '@/config/router';
import { langs } from '@/locales';
import lang from './lang';

const routes = [];

// 处理多语言&&单语言
if (langs.length > 1) {
    langs.forEach((key) => {
        rules.forEach((item) => {
            if (item) {
                routes.push({
                    ...item,
                    path: `/${key}/${item.path.replace(/^\/+/, '')}`,
                    meta: {
                        ...item.meta,
                    },
                });
            }
        });
    });
} else {
    rules.forEach((item) => {
        if (item) {
            routes.push({
                ...item,
                path: `/${item.path.replace(/^\/+/, '')}`,
                meta: {
                    ...item.meta,
                },
            });
        }
    });
}

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.addRoute({
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/pages/404'),
    meta: {
        title: 'layout.title',
        layout: 'flex',
    },
});

const install = arr => arr.forEach(item => router.beforeEach(item));

install(lang);

export default router;
